import 'package:flutter/material.dart';
import 'package:sunmi_nfc_manager/sunmi_nfc_manager.dart';

void main() {
  runApp(const MyApp());
}

class MyApp extends StatelessWidget {
  const MyApp({super.key});

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Sunmi NFC Manager Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
        useMaterial3: true,
      ),
      home: const NfcDemo(),
    );
  }
}

class NfcDemo extends StatefulWidget {
  const NfcDemo({super.key});

  @override
  State<NfcDemo> createState() => _NfcDemoState();
}

class _NfcDemoState extends State<NfcDemo> {
  final SunmiNfcManager _nfcManager = SunmiNfcManager();

  bool _isInitialized = false;
  List<NfcInfo> _nfcList = [];
  int _watermarkAlpha = 100;

  @override
  void initState() {
    super.initState();
    _initializePlugin();
  }

  @override
  void dispose() {
    _nfcManager.destroy();
    super.dispose();
  }

  Future<void> _initializePlugin() async {
    try {
      final initialized = await _nfcManager.initialize();

      setState(() {
        _isInitialized = initialized;
      });

      if (initialized) {
        _showSnackBar('NFC管理器初始化成功');
        await _refreshNfcList();
      } else {
        _showSnackBar('NFC管理器初始化失败');
      }
    } catch (e) {
      _showSnackBar('初始化失败: $e');
    }
  }

  Future<void> _refreshNfcList() async {
    try {
      final nfcList = await _nfcManager.getCurrentNfcList();
      setState(() {
        _nfcList = nfcList;
      });
      _showSnackBar('刷新成功: ${nfcList.length}个NFC模块');
    } catch (e) {
      _showSnackBar('刷新NFC列表失败: $e');
    }
  }

  Future<void> _switchNfc(String sn) async {
    if (!_isInitialized) {
      _showSnackBar('请先初始化NFC管理器');
      return;
    }

    try {
      final success = await _nfcManager.switchNfc(sn);
      if (success) {
        _showSnackBar('切换NFC模块成功: $sn');
      } else {
        _showSnackBar('切换NFC模块失败');
      }
    } catch (e) {
      _showSnackBar('切换NFC模块时出错: $e');
    }
  }

  Future<void> _setWatermarkAlpha(int alpha) async {
    if (!_isInitialized) {
      _showSnackBar('请先初始化NFC管理器');
      return;
    }

    try {
      final success = await _nfcManager.setNfcWaterMarkAlpha(alpha);
      if (success) {
        setState(() {
          _watermarkAlpha = alpha;
        });
        _showSnackBar('设置水印透明度成功: $alpha');
      } else {
        _showSnackBar('设置水印透明度失败');
      }
    } catch (e) {
      _showSnackBar('设置水印透明度时出错: $e');
    }
  }

  Future<void> _unregisterListener() async {
    if (!_isInitialized) {
      _showSnackBar('请先初始化NFC管理器');
      return;
    }

    try {
      final success = await _nfcManager.unregisterNfcListener();
      if (success) {
        _showSnackBar('取消注册监听器成功');
      } else {
        _showSnackBar('取消注册监听器失败');
      }
    } catch (e) {
      _showSnackBar('取消注册监听器时出错: $e');
    }
  }

  Future<void> _destroy() async {
    try {
      final success = await _nfcManager.destroy();
      if (success) {
        setState(() {
          _isInitialized = false;
          _nfcList = [];
        });
        _showSnackBar('NFC管理器已销毁');
      } else {
        _showSnackBar('销毁NFC管理器失败');
      }
    } catch (e) {
      _showSnackBar('销毁时出错: $e');
    }
  }

  void _showSnackBar(String message) {
    ScaffoldMessenger.of(context).showSnackBar(
      SnackBar(content: Text(message)),
    );
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('商米NFC管理器'),
        backgroundColor: Theme.of(context).colorScheme.inversePrimary,
      ),
      body: SingleChildScrollView(
        padding: const EdgeInsets.all(16.0),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            // 设备信息卡片
            Card(
              child: Padding(
                padding: const EdgeInsets.all(16.0),
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    Text(
                      '设备信息',
                      style: Theme.of(context).textTheme.headlineSmall,
                    ),
                    const SizedBox(height: 8),
                    Text('初始化状态: ${_isInitialized ? "已初始化" : "未初始化"}'),
                    Text('当前水印透明度: $_watermarkAlpha'),
                    Text('检测到NFC模块数: ${_nfcList.length}'),
                  ],
                ),
              ),
            ),

            const SizedBox(height: 16),

            // NFC列表卡片
            Card(
              child: Padding(
                padding: const EdgeInsets.all(16.0),
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    Row(
                      mainAxisAlignment: MainAxisAlignment.spaceBetween,
                      children: [
                        Text(
                          'NFC模块列表',
                          style: Theme.of(context).textTheme.headlineSmall,
                        ),
                        IconButton(
                          icon: const Icon(Icons.refresh),
                          onPressed: _isInitialized ? _refreshNfcList : null,
                          tooltip: '刷新NFC列表',
                        ),
                      ],
                    ),
                    const SizedBox(height: 8),
                    if (_nfcList.isEmpty)
                      const Padding(
                        padding: EdgeInsets.symmetric(vertical: 16.0),
                        child: Center(
                          child: Text('暂无NFC模块'),
                        ),
                      )
                    else
                      ListView.builder(
                        shrinkWrap: true,
                        physics: const NeverScrollableScrollPhysics(),
                        itemCount: _nfcList.length,
                        itemBuilder: (context, index) {
                          final nfc = _nfcList[index];
                          return Card(
                            margin: const EdgeInsets.only(bottom: 8),
                            child: ListTile(
                              leading: Icon(
                                nfc.isSelect ? Icons.nfc : Icons.nfc_rounded,
                                color:
                                    nfc.isSelect ? Colors.green : Colors.grey,
                              ),
                              title: Text('NFC模块${index + 1}'),
                              subtitle: Text('SN: ${nfc.sn}'),
                              trailing: Chip(
                                label: Text(
                                  nfc.isSelect ? '已选中' : '未选中',
                                  style: const TextStyle(fontSize: 12),
                                ),
                                backgroundColor: nfc.isSelect
                                    ? Colors.green.withOpacity(0.2)
                                    : Colors.grey.withOpacity(0.2),
                              ),
                              onTap: () => _switchNfc(nfc.sn),
                            ),
                          );
                        },
                      ),
                  ],
                ),
              ),
            ),

            const SizedBox(height: 16),

            // 水印透明度设置卡片
            Card(
              child: Padding(
                padding: const EdgeInsets.all(16.0),
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    Text(
                      '水印透明度设置',
                      style: Theme.of(context).textTheme.headlineSmall,
                    ),
                    const SizedBox(height: 16),
                    Text('当前值: $_watermarkAlpha'),
                    Slider(
                      value: _watermarkAlpha.toDouble(),
                      min: 0,
                      max: 100,
                      divisions: 10,
                      label: '$_watermarkAlpha',
                      onChanged: (value) {
                        setState(() {
                          _watermarkAlpha = value.round();
                        });
                      },
                      onChangeEnd: (value) {
                        _setWatermarkAlpha(value.round());
                      },
                    ),
                  ],
                ),
              ),
            ),

            const SizedBox(height: 16),

            // 控制按钮
            Card(
              child: Padding(
                padding: const EdgeInsets.all(16.0),
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    Text(
                      '管理操作',
                      style: Theme.of(context).textTheme.headlineSmall,
                    ),
                    const SizedBox(height: 16),

                    // 初始化/销毁按钮
                    Row(
                      children: [
                        Expanded(
                          child: ElevatedButton.icon(
                            onPressed:
                                !_isInitialized ? _initializePlugin : null,
                            icon: const Icon(Icons.play_arrow),
                            label: const Text('初始化'),
                            style: ElevatedButton.styleFrom(
                              backgroundColor: Colors.green,
                              foregroundColor: Colors.white,
                            ),
                          ),
                        ),
                        const SizedBox(width: 8),
                        Expanded(
                          child: ElevatedButton.icon(
                            onPressed: _isInitialized ? _destroy : null,
                            icon: const Icon(Icons.stop),
                            label: const Text('销毁'),
                            style: ElevatedButton.styleFrom(
                              backgroundColor: Colors.orange,
                              foregroundColor: Colors.white,
                            ),
                          ),
                        ),
                      ],
                    ),

                  ],
                ),
              ),
            ),

            const SizedBox(height: 16),

            // 快速设置透明度按钮
            Card(
              child: Padding(
                padding: const EdgeInsets.all(16.0),
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    Text(
                      '快速设置透明度',
                      style: Theme.of(context).textTheme.headlineSmall,
                    ),
                    const SizedBox(height: 8),
                    Wrap(
                      spacing: 8,
                      runSpacing: 8,
                      children: [
                        ElevatedButton(
                          onPressed: _isInitialized
                              ? () => _setWatermarkAlpha(0)
                              : null,
                          child: const Text('0%'),
                        ),
                        ElevatedButton(
                          onPressed: _isInitialized
                              ? () => _setWatermarkAlpha(25)
                              : null,
                          child: const Text('25%'),
                        ),
                        ElevatedButton(
                          onPressed: _isInitialized
                              ? () => _setWatermarkAlpha(50)
                              : null,
                          child: const Text('50%'),
                        ),
                        ElevatedButton(
                          onPressed: _isInitialized
                              ? () => _setWatermarkAlpha(75)
                              : null,
                          child: const Text('75%'),
                        ),
                        ElevatedButton(
                          onPressed: _isInitialized
                              ? () => _setWatermarkAlpha(100)
                              : null,
                          child: const Text('100%'),
                        ),
                      ],
                    ),
                  ],
                ),
              ),
            ),
          ],
        ),
      ),
    );
  }
}
